import Vue from 'vue'
import VueRouter from 'vue-router'

import Reg from '@/views/reg'
import Longin from '@/views/login'
import Layout from '@/views/layout'

import Home from '@/views/home'
import User from '@/views/user'

import UserPhoto from '@/views/userPhoto'
import ResetPswd from '@/views/resetpswd'
import Classify from '@/views/article/classify.vue'

// 导入vuex实例
import store from '@/store/index'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Longin
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/user-info',
        component: User
      },
      {
        path: '/user-avatar',
        component: UserPhoto
      },
      {
        path: '/user-pwd',
        component: ResetPswd
      },
      {
        path: '/art-cate',
        component: Classify
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const Vips = ['/login', '/reg']
  if (Vips.includes(to.path)) {
    next()
  } else {
    if (store.state.user.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
